package com.x.springboot.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.x.springboot.common.CommonResult;
import com.x.springboot.model.User;
import com.x.springboot.service.UserService;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author x.li
 * @since 2021-06-04
 */
@RestController
@RequestMapping("/weChat")
@Api(tags = "weChat控制器API")
public class WechatController {
    private static final Logger LOGGER = LoggerFactory.getLogger(WechatController.class);
    private static final String APPID = "wx3962309fe5e32006";
    private static final String SECRET  = "99973e320896b48bf477b41cf7f6bce7";

    /**
     * 前端向服务器获取code
     * @param response
     * @return
     * @throws IOException
     */
    @GetMapping("/getWxgzh")
    public String getWxgzh(HttpServletResponse response)throws IOException {
        // 第一步：用户同意授权，获取code
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+APPID
                + "&redirect_uri="+ URLEncoder.encode("http://22ue4w.natappfree.cc/user/getCode")
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE&connect_redirect=1#wechat_redirect";
        LOGGER.info("url="+url);
        response.sendRedirect(url);
        return "redirect:"+url;//必须重定向，否则不能成功
    }

    /**
     * 获取code的重定向方法
     * @param request
     * @return
     */
    @GetMapping("/getCode")
    public CommonResult getWxgzhApi(HttpServletRequest request){
        String code=request.getParameter("code");
        String state= request.getParameter("state");
        LOGGER.info("来了来了code="+code+",state="+state);
        if(StrUtil.isEmpty(code)){
            return CommonResult.failed("code为空");
        }
        Map<String,Object> openidMap = new HashMap<>();
        openidMap = getOpenId(APPID,SECRET,code);

        String openid = openidMap.get("openid")== null?null:openidMap.get("openid").toString();
        String access_token = openidMap.get("access_token")== null?null:openidMap.get("access_token").toString();

        if(StrUtil.isEmpty(openid) || StrUtil.isEmpty(access_token)){
            return CommonResult.failed("openid或access_token参数为空");
        }
        Map<String,Object> map = new HashMap<>();
        map = getUserInfo(openid,access_token);

        return CommonResult.success(map);
    }

    /**
     * 获取openid  access_token
     * @param appid
     * @param secret
     * @param code
     * @return
     */
    public static Map getOpenId(String appid, String secret, String code){
        String path = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid +
                "&secret="+secret+"&code="+code+"&grant_type=authorization_code";
        String res[] = requestJson(path);
        JSONObject jsonObject = JSON.parseObject(res[0]);
        String openid = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        Map<String,Object> map = new HashMap<>();
        map.put("openid",openid);
        map.put("access_token",access_token);

        return map;
    }


    /**
     * 获取用户信息
     * @param openid
     * @param access_token
     * @return
     */

    public static Map getUserInfo(String openid,String access_token){
        String path = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid;
        String res[] = requestJson(path);
        JSONObject jsonObject = JSON.parseObject(res[0]);
        //map对象
        Map<String, Object> map =new HashMap<>();

        //循环转换
        Iterator it =jsonObject.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = (Map.Entry<String, Object>) it.next();
            map.put(entry.getKey(), entry.getValue());
        }

        return map;

    }
    //get请求
    private static String[] requestJson(String url) {
        return request(url);
    }
    private static String[] request(String connurl) {
        String[] resultStr = new String[]{"", ""};
        StringBuilder resultData = new StringBuilder("");
        HttpURLConnection conn = null;
        try {
            URL url = new URL(connurl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setUseCaches(false);
            int mTimeout = 10000;
            conn.setConnectTimeout(mTimeout);
            conn.connect();
            int resultCode = conn.getResponseCode();
            InputStreamReader in;
            if (resultCode == 200) {
                in = new InputStreamReader(conn.getInputStream());
                BufferedReader buffer = new BufferedReader(in);
                String inputLine;
                while ((inputLine = buffer.readLine()) != null) {
                    resultData.append(inputLine);
                    resultData.append("\n");
                }
                buffer.close();
                in.close();
            }
            resultStr[0] = resultData.toString();
            resultStr[1] = resultCode + "";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return resultStr;
    }
}